package com.news.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.news.entity.Dept;
import org.news.entity.Emp;
import org.news.entity.User;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class TestJackson {
	public static void main(String[] args) throws Exception {
		test2();
	}
	//Jackson注解案例
	private static void test3() throws JsonProcessingException {
		Locale locale = Locale.getDefault();
		System.out.println(locale);
		User user = new User("1001", "张无忌", "123456");
		user.setBirthday(new Date());
		ObjectMapper mapper = new ObjectMapper();
		String jsonUser = mapper.writeValueAsString(user);
		System.out.println(jsonUser);
	}
	//反序列化对象
	private static void test2() throws IOException, JsonParseException,
			JsonMappingException {
		
		String jsonArray ="[{\"uid\":\"1001\",\"uname\":\"张无忌\",\"upwd\":\"123456\"},{\"uid\":\"1002\",\"uname\":\"赵敏\",\"upwd\":\"222222\"},{\"uid\":\"1003\",\"uname\":\"小昭\",\"upwd\":\"33333\"}]";
		String jsonUser ="{\"uid\":\"1001\",\"uname\":\"张无忌\",\"upwd\":\"123456\"}";
		ObjectMapper mapper = new ObjectMapper();
		User user = (User) mapper.readValue(jsonUser, User.class);
		System.out.println("对象:"+user);
		CollectionType ctype = TypeFactory.defaultInstance().constructCollectionType(ArrayList.class, User.class);
		Object readValue = mapper.readValue(jsonArray, ctype);
		System.out.println("集合:"+readValue);
	}
	//序列化对象
	private static void test1() throws JsonProcessingException {
		//普通对象
		User user = new User("1001", "张无忌", "123456");
		ObjectMapper mapper = new ObjectMapper();
		String jsonUser = mapper.writeValueAsString(user);
		System.out.println(jsonUser);
		//对象引用
		Dept dept = new Dept();
		dept.setDeptno(1000);
		dept.setDname("市场部");
		Emp emp = new Emp(1111,"李洁洁",new Date(),dept);
		String jsonEmp = mapper.writeValueAsString(emp);
		System.out.println(jsonEmp);
		//集合
		User user1 = new User("1001", "张无忌", "123456");
		User user2 = new User("1002", "赵敏", "222222");
		User user3 = new User("1003", "小昭", "33333");
		List<User> list = Arrays.asList(user1,user2,user3);
		String  jsonList= mapper.writeValueAsString(list);
		System.out.println(jsonList);
	}

}
